<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, View, Setting, Refresh, Download, HomeFilled, Clock, Mute, VideoPlay } from '@element-plus/icons-vue'
import axios from 'axios'

// 监控目标类型
interface MonitorTarget {
  id: number
  name: string
  type: string
  url: string
  frequency: number
  status: 'active' | 'paused' | 'error'
  lastChecked: string
  createdAt: string
  updatedAt: string
  description: string
  tags: string[]
  alertThreshold: number
}

// 监控目标类型选项
const targetTypes = [
  { value: 'website', label: '网站' },
  { value: 'api', label: 'API接口' },
  { value: 'social', label: '社交媒体' },
  { value: 'news', label: '新闻源' },
  { value: 'forum', label: '论坛' }
]

// 监控频率选项（分钟）
const frequencyOptions = [
  { value: 5, label: '5分钟' },
  { value: 15, label: '15分钟' },
  { value: 30, label: '30分钟' },
  { value: 60, label: '1小时' },
  { value: 360, label: '6小时' },
  { value: 720, label: '12小时' },
  { value: 1440, label: '24小时' }
]

// 状态过滤选项
const statusOptions = [
  { value: '', label: '全部' },
  { value: 'active', label: '活跃' },
  { value: 'paused', label: '已暂停' },
  { value: 'error', label: '异常' }
]

// 分页设置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索和过滤
const searchQuery = ref('')
const typeFilter = ref('')
const statusFilter = ref('')

// 加载状态
const loading = ref(false)

// 当前时间
const currentTime = ref(new Date())
const formattedTime = computed(() => {
  const options: Intl.DateTimeFormatOptions = { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit',
    hour12: false
  }
  return new Intl.DateTimeFormat('zh-CN', options).format(currentTime.value)
})

// 更新当前时间
const updateTime = () => {
  currentTime.value = new Date()
}

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('添加监控目标')
const dialogMode = ref<'add' | 'edit'>('add')

// 表单数据
const formData = reactive<MonitorTarget>({
  id: 0,
  name: '',
  type: 'website',
  url: '',
  frequency: 60,
  status: 'active',
  lastChecked: '-',
  createdAt: '',
  updatedAt: '',
  description: '',
  tags: [],
  alertThreshold: 70
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入目标名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入目标URL', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择目标类型', trigger: 'change' }
  ]
}

// 表单引用
const formRef = ref()

// 监控目标列表
const monitorTargets = ref<MonitorTarget[]>([])

// 获取监控目标列表
const fetchMonitorTargets = async () => {
  loading.value = true
  try {
    // 从后端API获取数据
    const response = await axios.get('/api/monitor-targets', {
      params: {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        type: typeFilter.value || undefined,
        status: statusFilter.value || undefined,
        search: searchQuery.value || undefined
      }
    })
    
    // 处理返回的数据
    monitorTargets.value = response.data.data || []
    pagination.total = response.data.total || 0
    
  } catch (error) {
    console.error('获取监控目标失败:', error)
    ElMessage.error('获取监控目标失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 筛选后的监控目标
const filteredTargets = computed(() => {
  // 如果使用后端分页和筛选，直接返回从后端获取的数据
  return monitorTargets.value
})

// 打开添加对话框
const openAddDialog = () => {
  dialogMode.value = 'add'
  dialogTitle.value = '添加监控目标'
  
  // 重置表单
  Object.assign(formData, {
    id: 0,
    name: '',
    type: 'website',
    url: '',
    frequency: 60,
    status: 'active',
    lastChecked: '-',
    createdAt: '',
    updatedAt: '',
    description: '',
    tags: [],
    alertThreshold: 70
  })
  
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (target: MonitorTarget) => {
  dialogMode.value = 'edit'
  dialogTitle.value = '编辑监控目标'
  
  // 填充表单数据
  Object.assign(formData, JSON.parse(JSON.stringify(target)))
  
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        if (dialogMode.value === 'add') {
          // 添加新目标
          const response = await axios.post('/api/monitor-targets', formData)
          if (response.data.success) {
            ElMessage.success('监控目标添加成功')
            // 刷新列表
            fetchMonitorTargets()
          } else {
            ElMessage.error(response.data.message || '添加失败')
          }
        } else {
          // 更新现有目标
          const response = await axios.put(`/api/monitor-targets/${formData.id}`, formData)
          if (response.data.success) {
            ElMessage.success('监控目标更新成功')
            // 刷新列表
            fetchMonitorTargets()
          } else {
            ElMessage.error(response.data.message || '更新失败')
          }
        }
        
        dialogVisible.value = false
      } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage.error('操作失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除监控目标
const deleteTarget = (target: MonitorTarget) => {
  ElMessageBox.confirm(
    `确定要删除监控目标"${target.name}"吗？此操作不可逆。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      const response = await axios.delete(`/api/monitor-targets/${target.id}`)
      if (response.data.success) {
        ElMessage.success('监控目标删除成功')
        // 刷新列表
        fetchMonitorTargets()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除监控目标失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 取消删除
  })
}

// 切换监控目标状态
const toggleTargetStatus = async (target: MonitorTarget) => {
  try {
    loading.value = true
    const newStatus = target.status === 'active' ? 'paused' : 'active'
    
    const response = await axios.patch(`/api/monitor-targets/${target.id}/status`, {
      status: newStatus
    })
    
    if (response.data.success) {
      ElMessage.success(`监控目标已${newStatus === 'active' ? '启用' : '暂停'}`)
      // 刷新列表
      fetchMonitorTargets()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('切换状态失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 导出监控目标数据
const exportData = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/monitor-targets/export', {
      params: {
        type: typeFilter.value || undefined,
        status: statusFilter.value || undefined,
        search: searchQuery.value || undefined
      },
      responseType: 'blob'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `监控目标数据_${new Date().toISOString().split('T')[0]}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchMonitorTargets()
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'active':
      return 'success'
    case 'paused':
      return 'info'
    case 'error':
      return 'danger'
    default:
      return 'default'
  }
}

// 获取状态显示文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'active':
      return '活跃'
    case 'paused':
      return '已暂停'
    case 'error':
      return '异常'
    default:
      return '未知'
  }
}

// 获取目标类型显示文本
const getTypeText = (type: string) => {
  const found = targetTypes.find(t => t.value === type)
  return found ? found.label : type
}

// 获取监控频率显示文本
const getFrequencyText = (frequency: number) => {
  const found = frequencyOptions.find(f => f.value === frequency)
  return found ? found.label : `${frequency}分钟`
}

// 组件挂载时
onMounted(() => {
  // 每秒更新时间
  setInterval(updateTime, 1000)
  
  // 获取监控目标列表
  fetchMonitorTargets()
})

// 标签输入相关
const inputVisible = ref(false)
const inputValue = ref('')
const tagInputRef = ref()

// 显示标签输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    tagInputRef.value.focus()
  })
}

// 处理标签输入确认
const handleInputConfirm = () => {
  if (inputValue.value) {
    if (!formData.tags.includes(inputValue.value)) {
      formData.tags.push(inputValue.value)
    }
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 修复slider的类型错误
const getFormatTooltip = (value: number): string => {
  return `${value}%`
}

// 监听分页、过滤器变化
watch([pagination.currentPage, pagination.pageSize, typeFilter, statusFilter, searchQuery], () => {
  fetchMonitorTargets()
}, { deep: true })
</script>

<template>
  <div class="monitor-targets-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">
          <el-icon><HomeFilled /></el-icon> 首页
        </el-breadcrumb-item>
        <el-breadcrumb-item>监控目标管理</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="current-time">
        <el-icon><Clock /></el-icon>
        <span>{{ formattedTime }}</span>
      </div>
    </div>
    
    <!-- 页面标题和控制区 -->
    <div class="page-header">
      <div class="title-section">
        <h1 class="page-title">监控目标管理</h1>
        <div class="page-description">
          管理和配置需要监控的目标对象，包括网站、API、社交媒体等
        </div>
      </div>
      
      <div class="header-actions">
        <el-button type="info" plain :icon="Download" @click="exportData">导出数据</el-button>
        <el-button type="primary" :icon="Plus" @click="openAddDialog">添加监控目标</el-button>
      </div>
    </div>
    
    <!-- 过滤器区域 -->
    <div class="filter-container">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索监控目标..."
          clearable
          :prefix-icon="Search"
        />
      </div>
      
      <div class="filter-section">
        <el-select v-model="typeFilter" placeholder="目标类型" clearable>
          <el-option
            v-for="item in targetTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <el-select v-model="statusFilter" placeholder="状态" clearable>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <el-button :icon="Refresh" circle @click="refreshData" :loading="loading" />
      </div>
    </div>
    
    <!-- 监控目标表格 -->
    <el-card shadow="hover" class="targets-table-card">
      <el-table
        :data="filteredTargets"
        border
        style="width: 100%"
        v-loading="loading"
        stripe
        table-layout="auto"
      >
        <el-table-column prop="name" label="目标名称" min-width="120">
          <template #default="scope">
            <div class="target-name">
              {{ scope.row.name }}
              <div class="tag-container">
                <el-tag v-for="tag in scope.row.tags" :key="tag" size="small" class="target-tag">
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="类型" width="80">
          <template #default="scope">
            {{ getTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="url" label="URL" min-width="150" show-overflow-tooltip />
        
        <el-table-column prop="frequency" label="监控频率" width="80">
          <template #default="scope">
            {{ getFrequencyText(scope.row.frequency) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="70">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" effect="light" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="lastChecked" label="最后检查时间" width="140" show-overflow-tooltip />
        
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-tooltip content="查看详情" placement="top">
                <el-button type="primary" :icon="View" circle size="small" />
              </el-tooltip>
              
              <el-tooltip :content="scope.row.status === 'active' ? '暂停监控' : '启用监控'" placement="top">
                <el-button
                  :type="scope.row.status === 'active' ? 'info' : 'success'"
                  :icon="scope.row.status === 'active' ? Mute : VideoPlay"
                  circle
                  size="small"
                  @click="toggleTargetStatus(scope.row)"
                />
              </el-tooltip>
              
              <el-tooltip content="编辑" placement="top">
                <el-button
                  type="warning"
                  :icon="Edit"
                  circle
                  size="small"
                  @click="openEditDialog(scope.row)"
                />
              </el-tooltip>
              
              <el-tooltip content="删除" placement="top">
                <el-button
                  type="danger"
                  :icon="Delete"
                  circle
                  size="small"
                  @click="deleteTarget(scope.row)"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          background
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="650px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="目标名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入监控目标名称" />
        </el-form-item>
        
        <el-form-item label="目标类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择目标类型" style="width: 100%">
            <el-option
              v-for="item in targetTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="目标URL" prop="url">
          <el-input v-model="formData.url" placeholder="请输入目标URL" />
        </el-form-item>
        
        <el-form-item label="监控频率" prop="frequency">
          <el-select v-model="formData.frequency" placeholder="请选择监控频率" style="width: 100%">
            <el-option
              v-for="item in frequencyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">活跃</el-radio>
            <el-radio label="paused">已暂停</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="标签" prop="tags">
          <el-tag
            v-for="tag in formData.tags"
            :key="tag"
            closable
            @close="formData.tags.splice(formData.tags.indexOf(tag), 1)"
            class="form-tag"
          >
            {{ tag }}
          </el-tag>
          
          <el-input
            v-if="inputVisible"
            ref="tagInputRef"
            v-model="inputValue"
            class="tag-input"
            size="small"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else size="small" @click="showInput">+ 添加标签</el-button>
        </el-form-item>
        
        <el-form-item label="告警阈值" prop="alertThreshold">
          <el-slider
            v-model="formData.alertThreshold"
            :min="0"
            :max="100"
            :format-tooltip="getFormatTooltip"
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入监控目标描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">
            {{ dialogMode === 'add' ? '添加' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.monitor-targets-view {
  padding: 20px;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.breadcrumb-container {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.current-time {
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
  margin-bottom: 8px;
}

.page-description {
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-section {
  flex: 1;
  min-width: 250px;
}

.filter-section {
  display: flex;
  gap: 10px;
  align-items: center;
}

.targets-table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: visible;
  width: 100%;
}

.target-name {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  margin-top: 4px;
}

.target-tag {
  margin-right: 4px;
  margin-bottom: 4px;
  font-size: 10px;
  padding: 0 5px;
  height: 20px;
  line-height: 18px;
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.form-tag {
  margin-right: 6px;
  margin-bottom: 6px;
}

.tag-input {
  width: 100px;
  margin-right: 6px;
  vertical-align: bottom;
}
</style>
